var user = require('/services/user.js');
const util = require('/utils/util.js');
const api = require('/config/api.js');

App({
  data:{
    userInfo: {},
},
  onLaunch: function () {
    var that=this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              this.globalData.userInfo = res.userInfo;
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              let userInfo = wx.getStorageSync('userInfo');
              let token = wx.getStorageSync('token');
      
              // 页面显示
              if (!(userInfo && token)) {
                wx.login({
                  success: function(res) {
                    if (res.code) {
                      util.request(api.AuthLoginByWeixin, {
                        code: res.code,
                        userInfo: that.globalData.userInfo
                      }, 'POST', 'application/json').then(res => {
                        if (res.resultCode === 0) {
                          //存储用户信息
                          wx.setStorageSync('userInfo', res.data.userInfo);
                          wx.setStorageSync('token', res.data.token);
                          wx.setStorageSync('userId', res.data.userInfo.id);
                          wx.switchTab({
                            url: '/pages/shop/index'
                          })
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: res.resultMsg,
                            showCancel: false
                          });
                        }
                      });
                    }
                  }
                });
              }

            }
          })
        }else{
          // wx.navigateTo({
          //   url: '/pages/auth/auth'
          // })
        }
      }
    })

    // 页面显示
    
  },
  globalData: {
    userInfo: {
      nickname: 'Hi,游客',
      username: '点击去登录',
      avatarurl: '/static/images/user.png'
    },
    token: '',
    userCoupon: 'NO_USE_COUPON',//默认不适用优惠券
    courseCouponCode: {},//购买课程的时候优惠券信息
    payStatus: null,//支付状态
    orderNo: null
  },
})